
package com.txd.mofa.shouye.aty;



import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.OnJumpResponseListener;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.adapter.TupianAdapter1;
import com.txd.mofa.base.BaseAty;
import com.txd.mofa.bean.ZhuangtaiBean;
import com.txd.mofa.bean.ZhuangtaiBean2;
import com.txd.mofa.fabu.aty.FabuAty;
import com.txd.mofa.login.BangdingAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.view.FenxiangDialog;
import com.txd.mofa.view.MyJzvdStd;
import com.txd.mofa.view.ShanchuDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.jzvd.Jzvd;

@Layout(R.layout.aty_two_t)
public class XiangqingAtySousuo extends BaseAty {

    private RecyclerView recy;
    private List<Map<String, String>> list1;
    private TupianAdapter1 tupianAdapter;
    private ImageView iv_back,iv,iv1;
    private ArrayList<Map<String, String>> data;
    private String name;
    private int pos1;
//    private TwinklingRefreshLayout refreshLayout;
//    private int page = 1;


    @SuppressLint("WrongConstant")
    @Override
    public void initViews() {
        super.initViews();
//        refreshLayout = findViewById(R.id.refreshLayout);
        recy = findViewById(R.id.recy);
        iv_back = findViewById(R.id.iv_back);
        iv = findViewById(R.id.iv);
        iv1 = findViewById(R.id.iv1);

        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(recy);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(me);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(linearLayoutManager);

        tupianAdapter = new TupianAdapter1(R.layout.item_tupian1);
        recy.setAdapter(tupianAdapter);

        List<Map<String,String>> list = new ArrayList<>();

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        woindex();

    }

    private void woindex() {
        HttpRequest.POST(me, woindex, new Parameter().add("token",token), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        Preferences.getInstance().set(me,"shouji","shouji",data.get("account"));

                    }


                }else {

                }
            }
        });
    }


    private String type = "";
    private boolean aaaa = false;

    private void http() {
        HttpRequest.POST(me, search, new Parameter().add("token", token).add("name", name), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {

                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")) {
                        data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));

                        if (aaaa == true){
                            if (page == 1) {

                                for (int i = 0; i < data.size(); i++) {

                                    zhi.add(data.get(i));
                                    zhi.get(i).put("flag", "111");
                                    zhi.get(i).put("qiehuan","222");
                                }


                                tupianAdapter.setNewData(zhi);


                            } else {

                                if (data == null || data.size() == 0) {
                                    return;
                                }

                                for (int i = 0; i < data.size(); i++) {
                                    data.get(i).put("flag", "111");
                                    data.get(i).put("qiehuan","222");
                                }



                                tupianAdapter.addData(data);


                            }

                        }else {
                            for (int i = 0; i < zhi.size(); i++) {

//                            zhi.add(data.get(i));
                                zhi.get(i).put("flag", "111");
//                                        zhi.get(i).put("qiehuan","222");
                            }


                            tupianAdapter.setNewData(zhi);

                            recy.scrollToPosition(pos1);
                            aaaa = true;

                        }

                    }

                } else {
                    toast("网络异常");
                }
            }
        });

    }
    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    private List<Map<String, String>> zhi;
    private int page = 1;

    @Override
    public void initDatas(JumpParameter paramer) {
        pos1 = getParameter().getInt("pos");
        zhi = (List<Map<String, String>>) getParameter().get("zhi");
        page = getParameter().getInt("page");
        http();
    }




    private int firstVisibleItem;
    private int lastVisibleItem;



    /**
     * 自动播放
     */
    private void autoPlayVideo(RecyclerView recyclerView) {

        if (firstVisibleItem == 0 && lastVisibleItem == 0 && recyclerView.getChildAt(0) != null) {

            MyJzvdStd videoView = null;
            if (recyclerView != null && recyclerView.getChildAt(0) != null) {
                videoView = recyclerView.getChildAt(0).findViewById(R.id.mp_video);
            }
            if (videoView != null) {
//                if (videoView.currentState == JZVideoPlayer.CURRENT_STATE_NORMAL || videoView.currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) {

                try {
                    videoView.startVideo();
                } catch (Exception e) {
                    videoView.setUp(list1.get(0).get("video_url"), "");
                    videoView.startVideo();
                }
//                }
            }
        }

        if (poss == 0) {
            for (int i = 0; i <= lastVisibleItem; i++) {
                if (recyclerView == null || recyclerView.getChildAt(i) == null) {
                    return;
                }


                MyJzvdStd videoView = recyclerView.getChildAt(i).findViewById(R.id.mp_video);
                if (videoView != null) {

                    Rect rect = new Rect();
                    //获取视图本身的可见坐标，把值传入到rect对象中
                    videoView.getLocalVisibleRect(rect);
                    //获取视频的高度
                    int videoHeight = videoView.getHeight();

                    if (rect.top <= 100 && rect.bottom >= videoHeight) {
//                    if (videoView.currentState == JZVideoPlayer.CURRENT_STATE_NORMAL || videoView.currentState == JZVideoPlayer.CURRENT_STATE_PAUSE) {

                        try {
                            videoView.startVideo();
                        } catch (Exception e) {
                            videoView.setUp(list1.get(i).get("video_url"), "");
                            videoView.startVideo();
                        }

//                    }
                        return;
                    }

                    MyJzvdStd.releaseAllVideos();

                } else {
                    MyJzvdStd.releaseAllVideos();
                }

            }
        }
    }


    private int pos = 0;
    private int posyuion = 0;
    private int poss = 1;


    @Override
    public void setEvents() {
//        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
//            @Override
//            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
////                        zhi.clear();
//                        page = 1;
//                        http();
//
//                    }
//                }, 2000);
//            }
//
//            @Override
//            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        page++;
//                        http();
//
//                    }
//                }, 2000);
//            }
//        });
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tupianAdapter.setPos(1);
                posyuion = 1;
                tupianAdapter.notifyDataSetChanged();
            }
        });

        iv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tupianAdapter.setPos(0);
                posyuion = 0;
                tupianAdapter.notifyDataSetChanged();
            }
        });


        tupianAdapter.setPageChange(new TupianAdapter1.PageChange() {
            @Override
            public void change(int pos,String s) {
                poss = pos;
                posyuion = pos;
                if (s.equals("1")) {
                    if (pos == 0) {
                        iv.setVisibility(View.VISIBLE);
                        iv1.setVisibility(View.GONE);
                    } else {
                        iv1.setVisibility(View.VISIBLE);
                        iv.setVisibility(View.GONE);
                    }
                }else {
                    iv1.setVisibility(View.GONE);
                    iv.setVisibility(View.GONE);
                }
            }
        });

        recy.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        /**在这里执行，视频的自动播放与停止*/
                        if (poss == 0) {
                            autoPlayVideo(recyclerView);
                        }
                        tupianAdapter.setPos(0);
                        tupianAdapter.notifyDataSetChanged();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        if (poss == 0) {
                            autoPlayVideo(recyclerView);
                        }
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        MyJzvdStd.releaseAllVideos();
                        break;
                }

            }
        });

        tupianAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<Map<String, String>> data = tupianAdapter.getData();

                switch (view.getId()){
                    case R.id.iv_qiehuan:
                        if (NetUtils.isNetworkAvailable(me)) {
                            if (Preferences.getInstance().getString(me,"shouji","shouji").equals("")){
                                Intent intent = new Intent(me, BangdingAty.class);
                                intent.putExtra("name","绑定手机号");
                                me.startActivity(intent);
                            }else {
                                if (tupianAdapter.getData().get(position).get("qiehuan").equals("111")) {
                                    tupianAdapter.getData().get(position).put("qiehuan", "222");
                                    tupianAdapter.getData().get(position).put("img", tupianAdapter.getData().get(position).get("beifen"));
                                    tupianAdapter.setPos(poss);
                                    EventBus.getDefault().post(new ZhuangtaiBean2(tupianAdapter.getData().get(position).get("collect"), "222",position));

                                    tupianAdapter.notifyDataSetChanged();
                                } else {
                                    if (Preferences.getInstance().getString(me, "face_img", "face_img").equals("")) {

                                        jump(FabuAty.class);

                                    } else {
                                        tupianAdapter.getData().get(position).put("beifen", tupianAdapter.getData().get(position).get("img"));
                                        qiehuan(position);

                                    }
                                }
                            }
                        }else {
                            Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                        }

                        break;

                    case R.id.iv_sc:
                        if (NetUtils.isNetworkAvailable(me)) {
                            if (Preferences.getInstance().getString(me,"shouji","shouji").equals("")){
                                Intent intent = new Intent(me, BangdingAty.class);
                                intent.putExtra("name","绑定手机号");
                                me.startActivity(intent);
                            }else {
                                if (data.get(position).get("collect").equals("1")) {
                                    ShanchuDialog shanchuDialog = new ShanchuDialog(me, "您确认要取消收藏？", new ShanchuDialog.SignListener() {
                                        @Override
                                        public void shanchu() {

                                            collectHttp(position);
                                        }
                                    });
                                    shanchuDialog.show();
                                } else {
                                    collectHttp(position);
                                }
                            }
                        }else {
                            Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                        }


                        break;

                    case R.id.iv_zhuanfa:
                        FenxiangDialog fenxiangDialog = new FenxiangDialog(me,poss, data.get(position), new FenxiangDialog.SignListener() {
                            @Override
                            public void jubao() {
                                if (NetUtils.isNetworkAvailable(me)) {
                                    jump(JubaoAty.class,
                                            new JumpParameter()
                                                    .put("id", data.get(position).get("id")).put("zhi", data)
                                                    .put("pos", position).put("page",1), new OnJumpResponseListener() {
                                                @Override
                                                public void OnResponse(JumpParameter jumpParameter) {
                                                    if (jumpParameter != null){
                                                        http();
                                                    }
                                                }
                                            });
                                }else {
                                    Toast.makeText(me, "网络连接不可用，请重试", Toast.LENGTH_SHORT).show();
                                }

                            }

                            @Override
                            public void fuzhi() {
                                ClipboardManager cmb = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                                if (data.get(position).get("video").equals("0")){
                                    cmb.setText(data.get(position).get("img"));
                                }else {
                                    cmb.setText(data.get(position).get("video"));
                                }

                                toast("已复制");
                            }
                        });
                        fenxiangDialog.show();
                        break;
                }
            }
        });

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void qiehuan(int position) {
        HttpRequest.POST(me, faceChang, new Parameter().add("token",token).add("hair_id",tupianAdapter.getData().get(position).get("id"))
                .add("user_img_url",Preferences.getInstance().getString(me,"face_img","face_img")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));

                        String fake_img_url = data.get("fake_img_url");

                        String fake_video_url = data.get("fake_video_url");

                        tupianAdapter.getData().get(position).put("qiehuan","111");
                        EventBus.getDefault().post(new ZhuangtaiBean2(tupianAdapter.getData().get(position).get("collect"), "111",position));


                        tupianAdapter.getData().get(position).put("img",fake_img_url);
                        tupianAdapter.getData().get(position).put("video",fake_video_url);

                        tupianAdapter.setPos(poss);

                        tupianAdapter.notifyDataSetChanged();


                    }

                }else {
                    toast("网络异常");
                }
            }
        });
    }

    private void collectHttp(int position) {
        HttpRequest.POST(me, isCollect, new Parameter().add("token",token).add("hair_id",tupianAdapter.getData().get(position).get("id")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){

                        if (tupianAdapter.getData().get(position).get("collect").equals("1")){
                            EventBus.getDefault().post(new ZhuangtaiBean2("2", tupianAdapter.getData().get(position).get("qiehuan"),position));

                            tupianAdapter.getData().get(position).put("collect","2");
                        }else {
                            EventBus.getDefault().post(new ZhuangtaiBean2("1", tupianAdapter.getData().get(position).get("qiehuan"),position));

                            tupianAdapter.getData().get(position).put("collect","1");
                        }
                        tupianAdapter.notifyDataSetChanged();

                    }
                }else {
                    toast("网络异常");
                }
            }
        });
    }

}
